<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model.trim="params.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="searchList"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          :data="list"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="handleTreeChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-permission'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeelist">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="departmentId" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <el-tag>{{ row.formOfEmployment === 1 ? '正式' : row.formOfEmployment === 2 ? '非正式' : '无' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column prop="" label="操作" width="280px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="updateDetail(row)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row)">角色</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="handleDelete(row)">
                <el-button slot="reference" style="margin-left: 10px;" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :page-size="params.pagesize"
            :current-page="params.page"
            @current-change="PageChange"
          />
        </el-row>
      </div>
    </div>
    <!-- <router-view /> -->
    <importExcel :show-excel-dialog.sync="showExcelDialog" @getEmployeeList="getEmployeeList" />

    <!-- 权限弹窗 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色" @close="roleClose">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="roleClose">取 消</el-button>
        <el-button size="mini" type="primary" @click="changeRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// \src\api\department.js / 左侧部门列表接口
import { getDepartments } from '@/api/department'
import { getTree } from '@/utils'
// \src\api\employee.js / 右侧员工接口
import { getEmployeeList, exportEmployee, delEmployee, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/importExcel.vue'
// 导入组件
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      // 部门列表
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }, // 树形组件属性
      params: {
        departmentId: null,
        page: 1,
        pagesize: 8,
        keyword: ''
      }, // 员工列表查询参数
      total: null, // 员工列表总数
      employeelist: [], // 员工列表数据
      timer: null,
      showExcelDialog: false,
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      roleId: null
    }
  },
  created() {
    this.getDepartmentsFn()
  },
  methods: {
    // 获取左侧部门列表
    async getDepartmentsFn() {
      this.list = getTree([...await getDepartments()], 0)
      this.params.departmentId = this.list[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕 获取到第一个节点 设置当前选中节点
        this.$refs.tree.setCurrentKey(this.params.departmentId)
      })
      this.getEmployeeList()
    },
    // 获取右侧员工列表
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.params)
      this.total = total
      this.employeelist = rows
    },
    // 树形组件切换事件 / 默认显示第一个节点并保存id
    handleTreeChange(data) {
      // console.log(data)
      this.params.departmentId = data.id
      this.params.page = 1
      this.getEmployeeList()
    },
    // 分页切换数据
    PageChange(page) {
      this.params.page = page
      this.getEmployeeList()
    },
    // 搜索员工
    searchList() {
      console.log(this.timer)
      // 清除之前的定时器
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 设置新的定时器
      this.timer = setTimeout(() => {
        this.params.page = 1
        this.getEmployeeList()
      }, 500)
    },
    // 导出员工
    async exportEmployee() {
      // 导出excel
      const res = await exportEmployee()
      console.log(res)
      FileSaver.saveAs(res, '员工列表.xlsx')
    },
    // 查看员工详情
    updateDetail(row) {
      this.$router.push(`/employee/detail?id=${row.id}`)
    },
    // 删除员工
    async handleDelete(row) {
      console.log(row)
      if (this.page > 1 && this.list.length === 1) {
        this.page--
      }
      await delEmployee(row.id)
      this.getEmployeeList()
    },
    // 查看权限
    async btnRole(row) {
      this.roleList = await getEnableRoleList()
      const res = await getEmployeeDetail(row.id)
      this.roleIds = res.roleIds
      this.roleId = row.id
      this.showRoleDialog = true
    },
    // 添加角色
    async changeRole() {
      await assignRole({
        id: this.roleId,
        roleIds: this.roleIds
      })
      this.roleClose()
    },
    // 清除角色弹框
    roleClose() {
      this.showRoleDialog = false
      this.roleIds = []
      this.roleId = null
      this.roleList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
